<?php
/**
 *
 * @author Martin "DevelX" Jurča
 */
class RSS extends Module {
    protected $name = 'RSS';
    protected $administrable = true;
    protected $version = '2010-04-16';
    protected $details = array('dependencies' => array(),
            'observes' => array('RSS'));

    const ITEMS = 'rssItems';

    protected $itemsTable = array('id' => 'iPN+', 'title' => 's', 'link' =>
            "v'1024'", 'description' => "v'4096'");

    protected $itemRecord = array('table' => self::ITEMS, 'data' => array());

    protected $title = '';
    protected $link = '';
    protected $description = '';
    protected $listLength = 0;
    protected $previewSize = 5;

    public function __construct(DBAPI $dbapi, RecordList $recordList) {
        parent::__construct($dbapi, $recordList);
        $this->itemRecord['properties'] = $this->itemsTable;
        if (file_exists($this->getDir('/settings'))) {
            $settings = unserialize(file_get_contents($this->
                    getDir('/settings')));
            foreach ($settings as $key => $value) {
                $this->{$key} = $value;
            }
        }
    }

    public function install() {
        FTP::createFile($this->getDir('/settings', true), 0666);
        $settings = array('title' => '', 'link' => '', 'description' => '',
                'listLength' => 10);
        file_put_contents($this->getDir('/settings'), serialize($settings));
        Modules::getModule('Users')->registerRights($this->getName(),
                $this->getRights());
        return $this->dbdriver->createTable(self::ITEMS, $this->itemsTable);
    }

    public function uninstall() {
        FTP::deleteFile($this->getDir('/settings', true));
        return $this->dbdriver->dropTable(self::ITEMS);
    }

    public function pushItem($title, $link, $description) {
        $item = $this->itemRecord;
        $item['data'] = array('title' => $title, 'link' => $link,
                'description' => $description);
        $this->dbapi->save($item);
        $this->generateRSS();
    }

    public function generateRSS() {
        $doc = new DOMDocument('1.0', 'UTF-8');
        $rss = $doc->createElement('rss', '');
        $rss->setAttribute('version', '2.0');
        $doc->appendChild($rss);
        $channel = $doc->createElement('channel', '');
        $rss->appendChild($channel);
        $title = $doc->createElement('title', $this->title);
        $channel->appendChild($title);
        $link = $doc->createElement('link', $this->link);
        $channel->appendChild($link);
        $description = $doc->createElement('description', $this->description);
        $channel->appendChild($description);
        $this->generateRSSItems($doc, $channel);
        if (!file_exists(Config::ROOT . '/rss.xml')) {
            FTP::createFile('/rss.xml', 0666);
        }
        if (!is_writeable(Config::ROOT . '/rss.xml')) {
            FTP::chmod('/rss.xml', 0666);
        }
        $doc->save(Config::ROOT . '/rss.xml');
    }

    public function onSettings(&$detail, $source) {
        if (!$this->hasRights('view admin')) {
            return;
        }
        $settings = array('title' => $detail['title'], 'link' =>
                $detail['link'], 'description' => $detail['description'],
                'listLength' => $detail['listLength']);
        file_put_contents($this->getDir('/settings'), serialize($settings));
        foreach ($settings as $key => $value) {
            $this->{$key} = $value;
        }
        $this->generateRSS();
    }

    public function onDelete(&$details, $source) {
        Kernel::setRedirect($this->getLink('list/'));
        if (!$this->hasRights('view admin')) {
            return;
        }
        $this->dbdriver->delete(self::ITEMS, '`id` = ' . (int) $details);
        $this->generateRSS();
    }

    public function displayPublicPreview() {
        $cols = array('title', 'link', 'description');
        $order = array('!id');
        $preview = &$this->dbdriver->select(self::ITEMS, $cols, '', $order, 0,
                $this->previewSize);
        $params = array('items' => &$preview);
        $this->template('preview', $params);
    }

    public function displayAdminIndex() {
        $form = array('start' => 'settings', 'legend' => 'settings',
                'submit' => 'save', 'items' => array(array('label' => 'title',
                'name' => 'title', 'value' => $this->title), array('label' =>
                'link', 'name' => 'link', 'value' => $this->link),
                array('label' => 'description', 'name' => 'description',
                'value' => $this->description), array('label' => 'listLength',
                'name' => 'listLength', 'value' => $this->listLength)));
        $this->prepareFormData($form);
        $params = array('form' => &$form);
        $this->template('form', $params);
    }

    public function displayAdminList() {
        $cols = array('id', 'title');
        $orderBy = array('!id');
        $list = &$this->dbdriver->select(self::ITEMS, $cols, '', $orderBy);
        foreach ($list as &$item) {
            $item['delete'] = $this->getLink($item['id'], 'delete');
        }
        $params = array('list' => &$list);
        $this->template('list', $params);
    }

    public function displayAdminSubmenu() {
        $menu = array(
            array('href' => '', 'label' => 'settings'),
            array('href' => 'list/', 'label' => 'list')
        );
        $this->prepareMenu($menu);
        $params = array('menu' => &$menu);
        $this->template('submenu', $params);
    }

    /**
     *
     * @param DOMDocument $doc
     * @param DOMElement $channel
     */
    private function generateRSSItems($doc, $channel) {
        $cols = array('title', 'link', 'description');
        $order = array('!id');
        $items = &$this->dbdriver->select(self::ITEMS, $cols, '', $order, 0,
                $this->listLength);
        foreach ($items as &$item) {
            $itemNode = $doc->createElement('item', '');
            $title = $doc->createElement('title', $item['title']);
            $itemNode->appendChild($title);
            $link = $doc->createElement('link', $item['link']);
            $itemNode->appendChild($link);
            $description = $doc->createElement('description', '');
            $descriptionText = $doc->createTextNode(
                    strip_tags($item['description']));
            $description->appendChild($descriptionText);
            $itemNode->appendChild($description);
            $channel->appendChild($itemNode);
        }
    }
}
?>
